package org.alex.jdk8.stream;

import static java.lang.System.err;
import static java.util.stream.Collectors.summarizingInt;

import java.util.Collections;
import java.util.HashSet;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.junit.After;
import org.junit.Test;

public class StreamTest1 {
	private boolean is_print;
	private Stream<UUID> uuids = Stream.generate(UUID::randomUUID).limit(100);
	private Locale[] locales = Locale.getAvailableLocales();
	private Stream<Locale> sls = Stream.of(locales).filter(a -> !"".equals(a.getCountry()));

	/**
	 * summaryStatistics 统计
	 */
	@Test
	public void max_min_avg_count() {
		Stream<Integer> sis = Stream.generate(Random::new).limit(100).map(Random::nextInt);
		IntSummaryStatistics iss = sis.collect(summarizingInt(a -> a));
		err.printf("max:%s,min:%s,avg:%s,count:%s", iss.getMax(), iss.getMin(), iss.getAverage(), iss.getCount());
	}

	@Test
	public void countryOfLanguage() {
		Map<String, String> col = sls.collect(Collectors.toMap(Locale::getDisplayCountry, Locale::getDisplayLanguage, (a, b) -> b));// 冲突保留后一个
		col.keySet().stream().forEach(a -> {
			err.printf("country:%s,Language:%s\n", a, col.get(a));
		});
	}

	/**
	 * 组合map
	 */
	@Test
	public void countryOfLocale() {
		Map<String, Locale> col = sls.collect(Collectors.toMap(Locale::getDisplayCountry, Function.identity(), (a, b) -> b));// 冲突保留后一个
		col.keySet().stream().forEach(a -> {
			err.printf("country:%s,Language:%s\n", a, col.get(a));
		});
	}

	/**
	 * 将国家语言列表
	 */
	@Test
	public void countryOfSetLocale() {
		Map<String, Set<String>> col = sls.collect(Collectors.toMap(Locale::getDisplayCountry, a -> Collections.singleton(a.getDisplayLanguage()), (a, b) -> {
			Set<String> r = new HashSet<String>();
			r.addAll(a);
			r.addAll(b);
			return r;
		}));
		col.keySet().stream().forEach(a -> {
			err.printf("国家:%s,语言:%s\n", a, col.get(a));
		});
	}
	/**
	 * 按照语言分组
	 */
	@Test
	public void group(){
		Map<String, List<Locale>> language2List=sls.collect(Collectors.groupingBy(Locale::getDisplayLanguage));
		language2List.keySet().stream().forEach(a -> {
			err.printf("语言:%s,国家:%s\n", a, language2List.get(a));
		});
	}
	/**
	 * 按照是否英语区分国家
	 */
	@Test
	public void partitioning(){
		Map<Boolean, List<Locale>> partitioning=sls.collect(Collectors.partitioningBy(a->a.getLanguage().equals("en")));
		partitioning.keySet().stream().forEach(a -> {
			err.printf("英语是否:%s,国家:%s\n", a, partitioning.get(a));
		});
	}

	@After
	public void after() {
		if (is_print) {
			uuids.forEach(err::println);
		}
	}
}
